package com.wbj.vpdirection.recycle

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.wbj.vpdirection.R
import com.wbj.vpdirection.mode.AngleData
import com.wbj.vpdirection.util.AltitudeUtil.dipToPx

open class DirectionView2 : LinearLayout {
    
    val tag: String = this::class.java.simpleName
    private val mAngleRange = 45
    private val mAnglePI = 360
    private val mAngleLimit = 22.5
    
    private val mInflater: LayoutInflater by lazy { LayoutInflater.from(context) }
    @SuppressLint("UseCompatLoadingForDrawables")
    private val dropDownDrawable: Drawable = context.resources.getDrawable(R.drawable.drop_down, context.theme)
    
    private val mDrawableWidth: Int by lazy { dipToPx(context, 15f) }
    private val mDrawableHeight: Int by lazy { dipToPx(context, 7.5f) }
    
    private val mFadingEdgeLength: Int by lazy { dipToPx(context, 500f) }
    val mSnapHelper: LinearSnapHelper by lazy { LinearSnapHelper() }
    
    private var mWidth: Int = context.resources.getDimensionPixelSize(R.dimen.recycler_view_compass_width)
    private var mHeight: Int = context.resources.getDimensionPixelSize(R.dimen.recycler_view_compass_height)
    private var mItemWidth: Int = context.resources.getDimensionPixelSize(R.dimen.recycler_item_view_compass_width)
    private val mSelectedCenterTextSize = context.resources.getDimensionPixelSize(R.dimen.compass_selected_text_size)
    private val mUnSelectCenterTextSize = context.resources.getDimensionPixelSize(R.dimen.compass_unselect_text_size)
    
    private lateinit var mRootView: View
    private lateinit var recyclerView: ShadowRecyclerView
    private lateinit var mLayoutManager: LinearLayoutManager
    private lateinit var list: MutableList<AngleData>
    private lateinit var adapter: DirectionAdapter
    
    private var centerView: TextView? = null
    private var isFirst = true
    
    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        initData()
        initView()
    }
    
    
    private fun initView() {
        mRootView = mInflater.inflate(R.layout.layout_direction_recyclerview, this)
        
        recyclerView = mRootView.findViewById(R.id.recyclerView)
        adapter = DirectionAdapter(context, list)
        recyclerView.adapter = adapter
        mLayoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        recyclerView.layoutManager = mLayoutManager
        recyclerView.addOnScrollListener(mScrollListener)
        mSnapHelper.attachToRecyclerView(recyclerView)
        
        recyclerView.overScrollMode = View.OVER_SCROLL_ALWAYS
        recyclerView.isHorizontalFadingEdgeEnabled = true
        recyclerView.setFadingEdgeLength(mFadingEdgeLength)
    }
    
    private fun initData() {
        list = mutableListOf()
        for (i in 0..7) {
            if (i == 0) {
                list.add(AngleData(345, 0, 15))
            } else {
                list.add(AngleData((3 * i - 1) * 15, 3 * i * 15, (3 * i + 1) * 15))
            }
        }
        //多出4个元素进行循环
        list.add(0, AngleData(300, 315, 330))
        list.add(0, AngleData(355, 270, 285))
        list.add(AngleData(345, 0, 15))
        list.add(AngleData(30, 45, 60))
        
    }
    
    fun updateCenterView() {
        if (centerView != null) {
            centerView?.textSize = mUnSelectCenterTextSize.toFloat()
            centerView?.isSelected = false
        }
        
        val view = mSnapHelper.findSnapView(mLayoutManager)
        view?.let {
            centerView = it.findViewById(R.id.tvCenterAngle)
            centerView?.textSize = mSelectedCenterTextSize.toFloat()
            centerView?.isSelected = true
        }
    }
    
    open fun setAngle(angle: Float) {
        angle.let {
            //取余360，除以22.5，toInt
            var rate = it.rem(mAnglePI).div(mAngleRange).toInt()
            if ((angle.minus(rate.times(mAngleRange))) >= mAngleLimit) {
                rate++
            }
            //当前数据 2-9有效，0、1、10、11无效，所以从1开始，实际数据要自增
            rate += 2
            
            val firstCompletelyVisible = mLayoutManager.findFirstCompletelyVisibleItemPosition()
            val itemView = mLayoutManager.findViewByPosition(firstCompletelyVisible)
            itemView?.measuredWidth.let { that ->
                if (that != null) {
                    mItemWidth = that
                }
            }
            mLayoutManager.scrollToPositionWithOffset(rate, (mWidth - mItemWidth).shr(1))
        }
    }
    
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val wSize = MeasureSpec.getSize(widthMeasureSpec)
        val hSize = MeasureSpec.getSize(heightMeasureSpec)
        if (mWidth <= wSize) {
            mWidth = wSize
        }
        if (mHeight <= hSize) {
            mHeight = hSize
        }
        setMeasuredDimension(mWidth, mHeight)
        
        if (isFirst){
            isFirst = false
            setAngle(0f)
        }
    }
    
    override fun dispatchDraw(canvas: Canvas) {
        super.dispatchDraw(canvas)
        dropDownDrawable.setBounds(
            (mWidth - mDrawableWidth).shr(1),
            0,
            (mWidth + mDrawableWidth).shr(1),
            mDrawableHeight
        )
        dropDownDrawable.draw(canvas)
    }
    
    
    private val mScrollListener = object : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            super.onScrollStateChanged(recyclerView, newState)
            Log.e(tag,"onScrollStateChanged:${newState},index:${recyclerView.indexOfChild(mSnapHelper.findSnapView(recyclerView.layoutManager))}"
            )
        }
        
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            Log.e(tag, "onScrolled:${dx},${dy},index:${recyclerView.indexOfChild(mSnapHelper.findSnapView(recyclerView.layoutManager))}")
            updateCenterView()
        }
    }
    
}

